package com.tian.arch.util

import android.content.SharedPreferences
import android.os.Parcelable
import com.tencent.mmkv.MMKV
import com.tian.arch.Foundation


/**
 * 用于替代 SharedPreferences 的工具
 *
 * @see <a href="https://github.com/Tencent/MMKV/wiki/android_tutorial_cn">MMKV<a/>
 */
object SpUtil {

    val spUtil by lazy { MMKV.defaultMMKV()!! }

    fun init() {
        MMKV.initialize(Foundation.context())
    }

    /**
     * 将数据从之前的 SharedPreferences 文件中，迁移到mmkv中
     */
    fun importFromSharedPreferences(oldSp: SharedPreferences) {
        spUtil.importFromSharedPreferences(oldSp)
    }

    fun put(key: String, value: Any) {
        when (value) {
            is Int -> spUtil.encode(key, value)
            is String -> spUtil.encode(key, value)
            is Boolean -> spUtil.encode(key, value)
            is Float -> spUtil.encode(key, value)
            is Long -> spUtil.encode(key, value)
            is Double -> spUtil.encode(key, value)
            is Parcelable -> spUtil.encode(key, value)
            else -> throw RuntimeException("current put value is not support")
        }
    }

    fun putStringSet(key: String, obj: Set<String>) {
        spUtil.putStringSet(key, obj)
    }

    fun getString(key: String, defaultValue: String = "") = spUtil.decodeString(key, defaultValue)
    fun getInt(key: String, defaultValue: Int = -1) = spUtil.decodeInt(key, defaultValue)
    fun getLong(key: String, defaultValue: Long = -1L) = spUtil.decodeLong(key, defaultValue)
    fun getFloat(key: String, defaultValue: Float = -1F) = spUtil.decodeFloat(key, defaultValue)
    fun getBoolean(key: String, defaultValue: Boolean = false) = spUtil.decodeBool(key, defaultValue)
    fun getDouble(key: String, defaultValue: Double = 0.0) = spUtil.decodeDouble(key, defaultValue)
    fun getStringSet(key: String) = spUtil.decodeStringSet(key).orEmpty()

    fun remove(key: String): SharedPreferences.Editor = spUtil.remove(key)
    fun clear() = spUtil.clearAll()

    inline fun <reified T : Parcelable> getParcelable(key: String, defaultValue: T? = null): T? {
        return spUtil.decodeParcelable(key, T::class.java, defaultValue)
    }

}